﻿// HSS.Data.ModelGenerator.Program.cs
// ----------------------------------------------------------------------------
// Licensed under the MIT license
// http://www.opensource.org/licenses/mit-license.html
// ----------------------------------------------------------------------------
// HighSpeed-Solutions, LLC
// Copyright (c) 2001-2010
// ----------------------------------------------------------------------------
// File:       Program.cs
// Author:     HSS\gbanta
// Created:    08/12/2010
// Modified:   12/07/2010
// ----------------------------------------------------------------------------
namespace HSS.Data.ModelGenerator
{
	#region Using Directives
	using System;
	using System.Text;
	using System.Windows.Forms;
	using HSS.Data;
	using HSS.Data.ModelGenerator;
	using HSS.Forms;
	using System.Reflection;
	#endregion

	#region Program
	/// <summary>
	/// DOMGen Program entry point.
	/// </summary>
	static class Program
	{
		#region Properties
		/// <summary>
		///  The Main Form for the application
		/// </summary>
		internal static MainForm MainForm
		{
			get;
			private set;
		}
		/// <summary>
		/// Gets the current connection string that but points to the Master dabase.
		/// </summary>
		internal static string MasterDBConnectionString
		{
			get
			{
				if (null != DataAccessContext.DefaultConnection)
				{
					DataAccessConnection dac = new DataAccessConnection(DataAccessContext.DefaultConnection);
					dac.InitialCatalog = string.Empty;
					string connstr = dac.ConnectionString;
					dac = null;
					return connstr;
				}
				return string.Empty;
			}
		}
		/// <summary>
		/// Gets the current AppContext.
		/// </summary>
		internal static AppContext<MainForm> Context
		{
			get;
			private set;
		}
		#endregion

		#region Methods

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			using (Program.Context = new AppContext<MainForm>())
				Program.Context.Run(args, InitializeApp);
		}

		static MainForm InitializeApp(string[] args, AppContext<MainForm> ctx)
		{
			ctx.ShowError += new EventHandler<SendExceptionEventArgs>(App_ShowError);
			ctx.SendException += new EventHandler<SendExceptionEventArgs>(App_SendException);

			AppUserConfiguration<TemplateData>.Refresh();

			if (AppUserConfiguration<TemplateData>.Items.Count == 0)
			{
				AppUserConfiguration<TemplateData>.AutoSave = false;

				AppUserConfiguration<TemplateData>.Add(
					new TemplateData()
					{
						Name = "DefaultTemplate",
						Contents = Templates.DefaultSingleFileTemplate
					});
				AppUserConfiguration<TemplateData>.Add(
					new TemplateData()
					{
						Name = "DefaultPartialEntityTemplate",
						Contents = Templates.DefaultPartialEntityFileTemplate
					});
				AppUserConfiguration<TemplateData>.Add(
					new TemplateData()
					{
						Name = "DefaultPartialContextTemplate",
						Contents = Templates.DefaultPartialContextFileTemplate
					});

				AppUserConfiguration<TemplateData>.Save();
				AppUserConfiguration<TemplateData>.AutoSave = true;
			}

			MainForm = new MainForm();

			Exception initError;
			if (!MainForm.Initialize(out initError))
			{
				if (null != initError)
					ShowUnableToStartError(initError.Message);
				else
					ShowUnableToStartError("Errors encountered starting application.");
				return null;
			}

			return MainForm;
		}

		static void SendExceptionAsync(Exception ex)
		{
			SendExceptionAsync(ex.ToString());
		}
		static void SendExceptionAsync(string message)
		{
			System.Threading.ThreadPool.QueueUserWorkItem(SendException, message);
		}
		static void SendException(object objMessage)
		{
			System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
			try { }
			finally
			{
				try
				{
					StringBuilder sb = new StringBuilder();
					sb.AppendFormat("Exception for: {0}\\{1}{2}{2}", Environment.UserDomainName, Environment.UserName, Environment.NewLine);
					sb.AppendFormat("DOMGen Version: {0}{1}{1}", typeof(Program).Assembly.GetName().Version.ToString(4), Environment.NewLine);
					sb.Append(objMessage.ToString());
					string message = sb.ToString();
					sb.Clear();
					sb = null;
					string subject = Application.ProductName + ": " + Properties.Resources.supportSubject;
					using (System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(Properties.Resources.exceptionUser, Properties.Resources.suppportEmail, subject, message))
						HSS.Net.Mail.SmtpClient.SendEmail(msg);
				}
				catch (Exception ex)
				{
					HSS.Logging.Log.WriteException(ex);
#if DEBUG
					MessageBox.Show(ex.ToString());
#endif
				}
			}
		}
		static void ShowUnableToStartError(string errorMsg)
		{
			string caption = string.Format(Properties.Resources.msgUnableToStartCaption, Application.ProductName);
			MessageBox.Show(errorMsg, caption, MessageBoxButtons.OK, MessageBoxIcon.Warning);
		}

		#endregion

		#region Event Handlers
		private static void App_ShowError(object sender, SendExceptionEventArgs e)
		{
			MessageBox.Show(e.UnhandledException.ToString(), "Exception Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
		}
		private static void App_SendException(object sender, SendExceptionEventArgs e)
		{
			if (e.SendException)
				SendExceptionAsync(e.UnhandledException);

			if (e.RestartApp)
				Application.Restart();
		}
		#endregion
	}
	#endregion
}